﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Server.Util;
using Server.Models;
using Newtonsoft.Json;

namespace Server.AuthService
{
    public class AuthDAL
    {
        CacheUtil cacheCtrl = new CacheUtil();
        DBUtil dbCtrl = new DBUtil();
        /// <summary>
        /// 检查用户权限
        /// </summary>
        /// <param name="id"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool CheckAuth(int id, string key)
        {
            try
            {
                string tmpStr = (string)cacheCtrl.CacheGet(string.Format("Manage_Auth:{0},{1}", id.ToString(), key));
                if (string.IsNullOrEmpty(tmpStr))
                    return false;
                tmpStr = JsonConvert.DeserializeObject<string>(tmpStr);
                if (string.IsNullOrEmpty(tmpStr))
                    return false;
                return true;
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 缓存检查用户权限
        /// </summary>
        public void CacheAuthInfo()
        {
            try
            {
                string sqlstr = " select t1.Uid,t2.FKey,t1.Aid from Manage_Author t1 left join Manage_Auth t2 on t1.Aid = t2.id ";
                var dt = dbCtrl.Query(sqlstr);
                if (null == dt)
                    throw new Exception("未知错误！");
                if (dt.Rows.Count < 1)
                {
                    cacheCtrl.CacheSet("Manage_Auth:Uid,Key", "", 1);
                    return;
                }
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    var dr = dt.Rows[i];
                    cacheCtrl.CacheSet(string.Format("Manage_Auth:{0},{1}", dr["Uid"], dr["FKey"]), "true");
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 获取权限列表
        /// </summary>
        public AuthListModel[] GetAuthCate()
        {
            try
            {
                string tmpStr = (string)cacheCtrl.CacheGet("Manage_AuthList");
                if (string.IsNullOrEmpty(tmpStr))
                    return CacheAuthListInfo();
                tmpStr = JsonConvert.DeserializeObject<string>(tmpStr);
                if (string.IsNullOrEmpty(tmpStr))
                    return null;
                AuthListModel[] authList = JsonConvert.DeserializeObject<AuthListModel[]>(tmpStr);
                return authList;
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 缓存并获取权限列表
        /// </summary>
        /// <returns></returns>
        public AuthListModel[] CacheAuthListInfo()
        {
            try
            {
                string sqlstr = "select distinct FCate from BS_Auth order by FCate";
                var dtFCate = dbCtrl.Query(sqlstr);
                AuthListModel[] authList = new AuthListModel[dtFCate.Rows.Count];
                for (int i = 0; i < dtFCate.Rows.Count; i++)
                {
                    authList[i] = new AuthListModel()
                    {
                        FCate = dtFCate.Rows[i]["FCate"].ToString()
                    };
                    sqlstr = string.Format("select * from BS_Auth where FCate = '{0}'", authList[i].FCate);
                    var dtList = dbCtrl.Query(sqlstr);
                    authList[i].FAuth = new AuthModel[dtList.Rows.Count];
                    for (int j = 0; j < dtList.Rows.Count; j++)
                    {
                        authList[i].FAuth[j] = new AuthModel()
                        {
                            Id = Convert.ToInt32(dtList.Rows[j]["id"]),
                            FCate = dtList.Rows[j]["FCate"].ToString(),
                            FKey = dtList.Rows[j]["FKey"].ToString(),
                            FDescription = dtList.Rows[j]["FDescription"].ToString()
                        };
                    }
                }

                cacheCtrl.CacheSet("Manage_Auth:AuthList", authList);
                return authList;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 获取用户对应权限
        /// </summary>
        /// <param name="uid"></param>
        /// <returns></returns>
        public AuthorModel[] GetAuthorList(int uid)
        {
            try
            {
                string tmpStr = (string)cacheCtrl.CacheGet("Manage_Author:Uid:" + uid);
                if (string.IsNullOrEmpty(tmpStr))
                    return null;
                tmpStr = JsonConvert.DeserializeObject<string>(tmpStr);
                if (string.IsNullOrEmpty(tmpStr))
                    return null;
                AuthorModel[] author = JsonConvert.DeserializeObject<AuthorModel[]>(tmpStr);
                return author;
            }
            catch (Exception)
            {
                throw;
            }
        }
        /// <summary>
        /// 缓存用户对应权限
        /// </summary>
        public void CacheAuthorList()
        {
            try
            {
                string sqlstr = " select distinct Uid from Manage_Author ";
                var dt = dbCtrl.Query(sqlstr);
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    sqlstr = string.Format(" select * from Manage_Author where uid = {0} ", dt.Rows[i]["Uid"]);
                    var Adt = dbCtrl.Query(sqlstr);
                    AuthorModel[] au = new AuthorModel[Adt.Rows.Count];
                    for (int j = 0; j < Adt.Rows.Count; j++)
                    {
                        au[i] = new AuthorModel()
                        {
                            Uid = Convert.ToInt32(dt.Rows[i]["Uid"]),
                            Aid = Convert.ToInt32(dt.Rows[i]["Aid"])
                        };
                    }
                    cacheCtrl.CacheSet("Manage_Author:Uid:" + dt.Rows[i]["Uid"],au);

                }
            }
            catch (Exception)
            {
                throw;
            }
        }

        public void SaveAuthorInfo(AuthorModel[] author)
        {
            try
            {
                string sqlstr = string.Format(" delete  from Manage_Author where uid = {0} ", author[0].Uid);
                dbCtrl.Exec(sqlstr);
                for (int i = 0; i < author.Length; i++)
                {
                    sqlstr = string.Format("insert into Manage_Author(aid,uid) values({0},{1})", author[i].Aid, author[i].Uid);
                    dbCtrl.Exec(sqlstr);
                }
                this.CacheAuthorList();
                this.CacheAuthListInfo();
                this.CacheAuthInfo();
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
